<?php

namespace App\Modules\LuckDraw\Models;

use App\Http\Model\User;
use Illuminate\Database\Eloquent\Model;

class AwardLogModel extends Model {
    protected $table = "luck_draw_award_log";

    //获得排行榜数据
    public static function ranking(int $luckId, int $top): array {
        $startDate = date('Y-m-d',time());
        $endDate = date('Y-m-d',strtotime('+1 day'));
        $selfTable = "luck_draw_award_log";
        $userTable = 'user';
        return self::query()
            ->select([$selfTable . '.luck_id', $selfTable . '.user_id',  $selfTable . '.award_id',
                $selfTable . '.type', $selfTable . '.time_limit', $selfTable . '.price', $selfTable . '.num', $selfTable . '.created_at',
                $userTable . '.nickname', $userTable . '.portrait'])
            ->where($selfTable .'.luck_id',$luckId)
            ->where($selfTable . '.created_at','>', $startDate)
            ->where($selfTable . '.created_at','<', $endDate)
            ->leftJoin($userTable,$selfTable . '.user_id', '=',  $userTable . '.user_id')
            ->orderBy($selfTable . '.price', 'desc')
            ->orderBy($selfTable . '.created_at', 'desc')
            ->limit($top)
            ->get()
            ->all();
    }

    //获得最新的中奖记录
    public static function latestAwards(int $luckId, int $top): array {
        $selfTable = "luck_draw_award_log";
        $userTable = 'user';
        return self::query()
            ->select([$selfTable . '.luck_id', $selfTable . '.user_id',  $selfTable . '.award_id',
                $selfTable . '.type', $selfTable . '.time_limit', $selfTable . '.price', $selfTable . '.num',
                $userTable . '.nickname'])
            ->where($selfTable .'.luck_id',$luckId)
            ->leftJoin($userTable,$selfTable . '.user_id', '=',  $userTable . '.user_id')
            ->orderBy($selfTable . '.id', 'desc')
            ->limit($top)
            ->get()
            ->all();
    }

    //status 表示是否已经将奖品发送的用户背包 返回插入的id
    public static function log(int $luckId,int $drawId, int $userId, int $poolId, string $strategy, int $awardId, int $type, int $num, int $price, int $timeLimit):int{
        $logModel = new AwardLogModel();
        $logModel->luck_id = $luckId;
        $logModel->draw_id = $drawId;
        $logModel->user_id = $userId;
        $logModel->pool = $poolId;
        $logModel->strategy = $strategy;
        $logModel->award_id = $awardId;
        $logModel->type = $type;
        $logModel->num = $num;
        $logModel->price = $price;
        $logModel->time_limit = $timeLimit;
        $logModel->save();
        return (int)$logModel->id;
    }
}